package cn.xxstudy.visitshop.ui.activity.main.fragment.train.viewmodel

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import cn.xxstudy.visitshop.network.ApiService
import cn.xxstudy.visitshop.ui.activity.main.fragment.train.model.TrainData
import java.lang.Exception

/**
 * @author ：DELL on 2021/3/26 .
 * @packages ：cn.xxstudy.visitshop.ui.activity.main.fragment.train.viewmodel .
 * TODO:数据源
 */
class TrainPagingSource : PagingSource<Int, TrainData>() {
    override fun getRefreshKey(state: PagingState<Int, TrainData>): Int? = null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, TrainData> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val trainData = ApiService.api().trainList(page, pageSize)
            val list = trainData.data.results
            //判断是否还有上一页
            val prevKey = if (trainData.data.previous.isNullOrEmpty()) null else page - 1
            //判断是否还有下一页
            val nextKey = if (trainData.data.next.isNullOrEmpty()) null else page + 1
            LoadResult.Page(list, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}